package com.springcloud.auth.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.util.UUID;

/**
 * Guocg
 * 2019/3/15
 */
public class GenerateUtil {

    private static String hashAlgorithmName = "SHA-256";
    private static int hashIterations = 5;
    private static boolean storedCredentialsHexEncoded = true;

    public static String geneUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /*public static String geneToken(String... strings) {
        long timestamp = System.currentTimeMillis();
        return DigestUtils.md5DigestAsHex((String.join("",strings) + timestamp).getBytes());
    }*/
    public static String geneCode() {
        return RandomStringUtils.randomNumeric(8);
    }

    /**
     * 生成密码
     *
     * @param pwd
     * @param salt
     * @return
     */
    public static String genePwd(String pwd, String salt) {

        if (storedCredentialsHexEncoded) {
            return new SimpleHash(hashAlgorithmName, pwd, salt, hashIterations).toHex();
        } else {
            return new SimpleHash(hashAlgorithmName, pwd, salt, hashIterations).toString();
        }
    }

    /**
     * 生成盐
     *
     * @param text
     * @return
     */
    public static String getSalt(String text) {
        Md5Hash md5 = new Md5Hash(text);
        md5.setIterations(hashIterations);
        return md5.toHex();
    }

    /**
     * 校验密码
     *
     * @param encPass
     * @param password 原文
     * @param userSalt
     * @return
     */
    public static boolean isValidPwd(String encPass, String password, String userSalt) {
        if (storedCredentialsHexEncoded) {
            return new SimpleHash(hashAlgorithmName, password, userSalt, hashIterations).toHex().equals(encPass);
        } else {
            return new SimpleHash(hashAlgorithmName, password, userSalt, hashIterations).toString().equals(encPass);
        }
    }

    public static void main(String[] args) {

        String salt = GenerateUtil.getSalt("azsx220");
        String decodePwd = GenerateUtil.genePwd("123", salt);
        System.out.println(decodePwd);
    }
}
